package com.itemp.ms66scan;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import androidx.appcompat.app.AppCompatActivity;

/**
 * WIFI P2P
 */
public class ClientActivity extends AppCompatActivity {
    private WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel channel;
    private BroadcastReceiver receiver;
    private WifiP2pDevice serverDevice;
    private Socket socket;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);

        // 初始化 WifiP2pManager
        wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        if (wifiP2pManager == null) {
            Toast.makeText(this, "该设备不支持 Wi-Fi Direct", Toast.LENGTH_SHORT).show();
            return;
        }

        // 初始化 Channel
        channel = wifiP2pManager.initialize(this, getMainLooper(), null);

        // 注册广播接收器
        receiver = new BroadcastReceiver() {
            @SuppressLint("MissingPermission")
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
                    // Wi-Fi Direct 状态发生变化
                    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        Log.d("Client", "Wi-Fi Direct 已启用");
                    } else {
                        Log.d("Client", "Wi-Fi Direct 已停用");
                    }
                } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                    // 设备列表发生变化
                    wifiP2pManager.requestPeers(channel, peers -> {
                        for (WifiP2pDevice device : peers.getDeviceList()) {
                            Log.d("Client", "发现设备：" + device.deviceName + ", " + device.deviceAddress);

                            // 记录服务端设备
                            if (device.deviceName.equals("server")) {
                                serverDevice = device;
                            }
                        }
                    });
                } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                    // 连接状态发生变化
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo.isConnected()) {
                        // 建立连接
                        Log.d("Client", "连接已建立");

                        // 请求连接信息
                        wifiP2pManager.requestConnectionInfo(channel, info -> {
                            if (info.groupFormed && info.isGroupOwner) {
                                // 服务端不需要做额外处理
                                Log.d("Client", "该设备为服务端");

                            } else if (info.groupFormed) {
                                // 客户端发起连接
                                Log.d("Client", "该设备为客户端");

                                try {
                                    socket = new Socket();
                                    socket.connect(new InetSocketAddress(serverDevice.deviceAddress, 8888), 5000);
                                    Log.d("Client", "连接服务器成功：" + socket.getInetAddress());
                                    // 向服务端发送数据
                                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                                    writer.write("Hello, World!");
                                    writer.newLine();
                                    writer.flush();
                                    // 读取服务端响应数据
                                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                    String data = reader.readLine();
                                    Log.d("Client", "服务端返回的响应：" + data);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        // 断开连接
                        Log.d("Client", "连接已断开");
                        if (socket != null) {
                            try {
                                socket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
                    // 本设备信息发生变化
                    WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
                    Log.d("Client", "本设备信息发生变化：" + device.deviceName + ", " + device.deviceAddress);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        registerReceiver(receiver, filter);

        // 扫描设备
        wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.d("Client", "开始查找设备");
            }

            @Override
            public void onFailure(int reason) {
                Log.d("Client", "查找设备失败：" + reason);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭客户端 Socket
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 注销广播接收器
        unregisterReceiver(receiver);
    }
}
